﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Net.DesignByContract;

namespace Common.Net.DataStructures
{
    public delegate bool EqualityComparison<T>(T left, T right);

    public static class EqualityComparisonHelper
    {
        public static IEqualityComparer<T> GetComparer<T>(this EqualityComparison<T> comparisonDelegate)
        {
            return new DelegateBasedEqualityComparer<T>(comparisonDelegate);
        }

        public static IEqualityComparer<T> GetComparer<T>(this Func<T, T, bool> comparisonDelegate)
        {
            EqualityComparison<T> equalityComparison = (left, right) => comparisonDelegate(left, right);

            return GetComparer(equalityComparison);
        }

        class DelegateBasedEqualityComparer<T> : IEqualityComparer<T>
        {
            readonly EqualityComparison<T> _comparison;

            public DelegateBasedEqualityComparer(EqualityComparison<T> comparison)
            {
                RequireArg.NotNull(() => comparison);

                _comparison = comparison;
            }

            #region IEqualityComparer<T> Members

            public bool Equals(T x, T y)
            {
                return _comparison(x, y);
            }

            public int GetHashCode(T obj)
            {
                return 0; // Dummy implementation. This should not be in IEqualityComparer<T> at all
            }

            #endregion
        }
    }
}
